package cn.stylefeng.guns.modular.gridsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.gridsystem.entity.BizException;
import cn.stylefeng.guns.modular.gridsystem.entity.BizExceptionLog;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizExceptionMapper;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizExceptionLogParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizExceptionParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.*;
import cn.stylefeng.guns.modular.gridsystem.mqtt.result.FaultHistory;
import cn.stylefeng.guns.modular.gridsystem.service.BizExceptionLogService;
import cn.stylefeng.guns.modular.gridsystem.service.BizExceptionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 故障表 服务实现类
 *
 * @author ssy
 * @date 2021/09/14 11:47
 */
@Service
public class BizExceptionServiceImpl extends ServiceImpl<BizExceptionMapper, BizException> implements BizExceptionService {

    @Resource
    private BizExceptionLogService bizExceptionLogService;

    @Override
    public PageResult<BizException> page(BizExceptionParam bizExceptionParam) {

        // 构造条件
        LambdaQueryWrapper<BizException> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BizException> list(BizExceptionParam bizExceptionParam) {

        // 构造条件
        LambdaQueryWrapper<BizException> queryWrapper = new LambdaQueryWrapper<>();
        if (bizExceptionParam != null && ObjectUtil.isNotEmpty(bizExceptionParam.getDeviceId())) {
            queryWrapper.eq(BizException::getDeviceId, bizExceptionParam.getDeviceId());
        }
        return this.list(queryWrapper);
    }

    @Override
    public void add(BizExceptionParam bizExceptionParam) {

        // 将dto转为实体
        BizException bizException = new BizException();
        BeanUtil.copyProperties(bizExceptionParam, bizException);

        this.save(bizException);
    }

    @Override
    public int addAndReturnId(BizExceptionParam bizExceptionParam) {
        this.baseMapper.insertAndReturnId(bizExceptionParam);
        return bizExceptionParam.getId();
    }

    @Override
    public PageResult<BizExceptionResult> pageList(BizExceptionParam param) {
        if (ObjectUtil.isEmpty(param.getStationId())) {
            param.setStationId(0);
        }
        Page<BizExceptionResult> page = this.baseMapper.page(PageFactory.defaultPage(), param);
        return new PageResult<>(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(BizExceptionParam bizExceptionParam) {
        //获取对应的子故障删除
        final LambdaQueryWrapper<BizExceptionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizExceptionLog::getExceptionId, bizExceptionParam.getId());
        List<BizExceptionLog> list = bizExceptionLogService.list(queryWrapper);
        for (BizExceptionLog exceptionLog:list){
            BizExceptionLogParam bizExceptionLogParam = new BizExceptionLogParam();
            // 请求参数转化为实体
            BeanUtil.copyProperties(exceptionLog, bizExceptionLogParam);
            bizExceptionLogService.delete(bizExceptionLogParam);
        }

        this.removeById(bizExceptionParam.getId());
    }

    @Override
    public void edit(BizExceptionParam bizExceptionParam) {

        // 根据id查询实体
        BizException bizException = this.queryBizException(bizExceptionParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(bizExceptionParam, bizException);

        this.updateById(bizException);
    }

    @Override
    public BizException detail(BizExceptionParam bizExceptionParam) {
        return this.queryBizException(bizExceptionParam);
    }

    @Override
    public void changeStatus(BizExceptionParam bizExceptionParam) {
        Integer id = bizExceptionParam.getId();
        Integer status = bizExceptionParam.getStatus();

        // 更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<BizException> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(BizException::getId, id)
                .set(BizException::getStatus, status)
                .set(BizException::getUpdateTime, DateUtil.date());
        this.update(updateWrapper);
    }

    /**
     * 错误的名字,今天列表
     */
    @Override
    public BizException listByErrorNameAndToday(BizExceptionParam bizExceptionParam) {
        QueryWrapper<BizException> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", bizExceptionParam.getDeviceId());
        queryWrapper.eq("error_name", bizExceptionParam.getErrorName());
        queryWrapper.eq("gateway_code", bizExceptionParam.getGatewayCode());
        queryWrapper.eq("DATE_FORMAT(created_at,'%Y-%m-%d')", DateUtil.formatDate(DateUtil.parseDate(bizExceptionParam.getCreatedAt())));
        queryWrapper.orderByDesc("created_at");
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    /**
     * 获取故障表
     *
     * @author ssy
     * @since 2021/09/14 11:47
     */
    private BizException queryBizException(BizExceptionParam bizExceptionParam) {
        BizException bizException = this.getById(bizExceptionParam.getId());
        return bizException;
    }

    public Map<String, Long> countStatus(Integer deviceId) {
        return this.baseMapper.countStatus(deviceId);
    }

    @Override
    public List<ExceptionCountDataResult> getErrorCountByMonth(Integer stationId) {
        return this.baseMapper.getErrorCountByMonth(stationId);
    }

    @Override
    public PageResult<FaultHistory> queryFaultHistory(Page page, String startTime, String endTime) {
        // 查询分页结果
        return new PageResult<>(this.baseMapper.faultHistoryPage(page, startTime,endTime));
    }

    @Override
    public List<BizExceptionResult> getDeviceExceptionList(Integer stationId,Integer deviceId, String startTime, String endTime) {
        return this.baseMapper.getDeviceExceptionList(stationId,deviceId,startTime,endTime);
    }

}
